package service

import (
	"common/biz"
	"common/net"
	"common/utils"
	"context"
	"core/dao"
	"core/repo"
	"fmt"
	"framework/game"
	"framework/msError"
	"user/pb"
)

type SmsService struct {
	accountDao *dao.AccountDao
	redisDao   *dao.RedisDao
	pb.UnimplementedSendSmsServiceServer
}

func NewSmsService(manager *repo.Manager) *SmsService {
	return &SmsService{
		accountDao: dao.NewAccountDao(manager),
		redisDao:   dao.NewRedisDao(manager),
	}
}

func (s *SmsService) Register(ctx context.Context, req *pb.SendSmsParams) (*pb.SendSmsResponse, error) {
	get := s.redisDao.RGet(ctx, req.Account)
	if get != "" {
		return &pb.SendSmsResponse{}, msError.GrpcError(biz.SmsSendFailed)
	}
	accessKeyId := game.Conf.GameConfig["sms_auth_config"]["value"].(map[string]any)["access_key_id"].(string)
	accessKeySecret := game.Conf.GameConfig["sms_auth_config"]["value"].(map[string]any)["access_key_secret"].(string)
	signName := game.Conf.GameConfig["sms_auth_config"]["value"].(map[string]any)["sign_name"].(string)
	templateCode := game.Conf.GameConfig["sms_auth_config"]["value"].(map[string]any)["template_code"].(string)
	code := utils.Random(100000, 999999)
	//redis.set
	sms := net.AliyunSendSMS(accessKeyId, accessKeySecret, signName, templateCode, fmt.Sprintf("%d", code), req.Account)
	if *sms.Body.Code != "OK" {
		return &pb.SendSmsResponse{}, msError.GrpcError(biz.SmsSendFailed)
	}
	err := s.redisDao.RSet(ctx, req.Account, fmt.Sprintf("%d", code), 600)
	if err != nil {
		return &pb.SendSmsResponse{}, msError.GrpcError(biz.SqlError)
	}
	return &pb.SendSmsResponse{}, nil
}
